package cn.hp.service.impl;
import cn.hp.entity.Menu;
import cn.hp.entity.User;
import cn.hp.entity.UserRole;
import cn.hp.mapper.MenuMapper;
import cn.hp.mapper.UserMapper;
import cn.hp.mapper.UserRoleMapper;
import cn.hp.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private MenuMapper menuMapper;
    @Resource
    private UserRoleMapper userRoleMapper;



    @Override
    public List<User> selectUser(User user) {
        return userMapper.selectUser(user);
    }

    @Override
    public PageInfo<User> selectUser(User user, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        List<User> list = userMapper.selectUser(user);
        return new PageInfo<>(list);
    }

    @Override
    @Transactional
    public int insertUser(User user) {
        int k = userMapper.insertUser(user);
        Integer[] roleids = user.getRoleIds();
        for (int i = 0;i < roleids.length; i++){
            Integer roleid = roleids[i];
            UserRole userRole = new UserRole();
            userRole.setRoleId(roleid).setUid(user.getId());
            k += userRoleMapper.insertUserRole(userRole);
        }
        return k;
    }

    @Override
    @Transactional
    public int updateUser(User user) {
        //第一步 删除RoleMenu中的信息
        userRoleMapper.deleteUserRoleByUid(user.getId());
        //第二步 修改角色信息
        int k = userMapper.updateUser(user);
        //第三步 将角色菜单信息再次插入role_menu
        Integer[] roleids = user.getRoleIds();
        for (int i = 0;i < roleids.length; i++){
            Integer roleid = roleids[i];
            UserRole userRole = new UserRole();
            userRole.setRoleId(roleid).setUid(user.getId());
            k += userRoleMapper.insertUserRole(userRole);
        }
        return k;
    }

    @Override
    @Transactional
    public int deleteUserById(Integer id) {
        int k = userRoleMapper.deleteUserRoleByUid(id);
        return userMapper.deleteUserById(id);
    }


    @Override
    public int resetPassword(User user) {
        return userMapper.updateUser(user);
    }

    @Override
    public List<Menu> selectUidMenu(User user) {
        return menuMapper.selectUidMenu(user);
    }

    @Override
    public User doLogin(User user) {
        List<User> list = userMapper.findUserByEmailAndPassword(user);
        return list.size() > 0 ? list.get(0) : null;
    }


}

